from fastapi import APIRouter, Query
from tortoise.expressions import Q

from app.settings import settings
from app.models.admin import Downloads
from app.schemas import SuccessExtra
from app.core.dependency import DependPermisson
from app.core.ctx import CTX_USER_ID
from app.schemas import Success, SuccessExtra,Fail
from pathlib import Path
from fastapi.responses import FileResponse
import os
import mimetypes

downloads_router = APIRouter()

@downloads_router.get('/list', summary="下载文件列表", dependencies=[DependPermisson])
async def get_downloads_list(
    page: int = Query(1, description="页码"),
    page_size: int = Query(10, description="每页数量"),
    start_time: str = Query("", description="开始时间"),
    end_time: str = Query("", description="结束时间"),
    name: str = Query(None, description="文件名"),
):
    user_id = CTX_USER_ID.get()
    q = Q()
    if name:
        q &= Q(name__contains=name)
    if user_id:
        q &= Q(user_id=user_id)
    if start_time and end_time:
        q &= Q(created_at__range=[start_time, end_time])
    elif start_time:
        q &= Q(created_at__gte=start_time)
    elif end_time:
        q &= Q(created_at__lte=end_time)

    objs = await Downloads.filter(q).offset((page - 1) * page_size).limit(page_size).order_by("-created_at")
    total = await Downloads.filter(q).count()
    data = [await download.to_dict() for download in objs]
    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)

@downloads_router.get('/down', summary="点击下载", dependencies=[DependPermisson])
async def get_download(
    data_id: int = Query(0, description="文件id"),
):
    ret = await Downloads.filter(id=data_id).get()
    url = ret.url
    name = ret.name
    file_path = Path(url)
    count = ret.count + 1
    print("count",count)
    await Downloads.filter(id=data_id).update(state=1,count=count)
    return FileResponse(path=file_path, filename=name+".xlsx", media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')

@downloads_router.get('/files', summary="文件夹列表", dependencies=[DependPermisson])
async def get_downloads_list(
    path: str = Query(None, description="文件夹名称"),
):
    data = []
    if path == "/":
        path = settings.UPLOAD_FOLDER + "/"

    # 获取该目录下的所有条目
    entries = os.listdir(path)

    # 通过列表推导式分别获取文件和文件夹
    files = [entry for entry in entries if os.path.isfile(os.path.join(path, entry))]
    files.sort(key=lambda f: os.path.getctime(os.path.join(path, f)), reverse=True)
    subfolders = [entry for entry in entries if os.path.isdir(os.path.join(path, entry))]

    for name in subfolders:
        item = {
            "file_type":1,
            "name":name,
            "path":path+name+'/'
        }
        data.append(item)
    for file in files:
        _, ext = os.path.splitext(file)

        file_ext = ext.lstrip('.')  # 去掉开头的点
        if file_ext in settings.ALLOWED_IMAGES:
            file_type = 2
        else:
            file_type = 3
        item2 = {
            "file_type":file_type,
            "name":file,
            "path":"",
            "url":settings.APP_IP+path+file,
            "file_ext": file_ext,
        }
        data.append(item2)

    ret = {
        "list":data,
        "path":path
    }
    return SuccessExtra(data=ret)

@downloads_router.get('/delete_file', summary="删除文件", dependencies=[DependPermisson])
async def get_downloads_list(
    path: str = Query(None, description="文件路径"),
):
    file_path  = path.replace(settings.APP_IP, "")
    # 检查文件是否存在
    if os.path.exists(file_path):
        os.remove(file_path)
    return Success(msg="删除成功")

@downloads_router.get('/download_file', summary="下载文件", dependencies=[DependPermisson])
async def get_download(
    path: str = Query(None, description="文件路径"),
):
    file_path  = path.replace(settings.APP_IP, "")
    # 检查文件是否存在
    if not os.path.exists(file_path):
        return Fail(msg="文件未找到")

    # 自动推断文件的MIME类型
    mime_type, _ = mimetypes.guess_type(file_path)

    if mime_type is None:
        mime_type = 'application/octet-stream'  # 如果无法推断类型，则使用通用二进制流类型

    # 提取文件名（不带路径）
    file_name = os.path.basename(file_path)

    # 返回文件响应
    return FileResponse(path=file_path, filename=file_name, media_type=mime_type)



